package account.webapi;

import account.pojo.StudentAccount;

import java.io.Serializable;
import java.time.LocalDate;
import java.time.Period;

class MaskedStudentAccount implements Serializable {
    /**
     * 主键
     */
    private Long id;

    /**
     * 打码后的姓名, 例如: 张某, 李某, 孙某空, 猪某戒
     */
    private String maskedName;

    /**
     * 年龄(应根据出生日期进行换算)
     */
    private Integer age;

    /**
     * 打码后的手机号码, 例如: 130****9876
     */
    private String maskedMobilePhoneNumber;

    /**
     * 不允许new
     */
    protected MaskedStudentAccount() {
        id = null;
        maskedName = null;
        age = null;
    }

    /**
     * StudentAccount 包装器。用法如下：
     * <p>
     * MaskedStudentAccount.of(StudentAccount account)
     */
    public static MaskedStudentAccount of(StudentAccount account) {
        MaskedStudentAccount rebuilt = new MaskedStudentAccount();
        rebuilt.id = account.getId();
        rebuilt.maskedName = maskedNameOf(account.getRealName());
        rebuilt.age = ageFromDateOfBirth(account.getDob());
        rebuilt.maskedMobilePhoneNumber = maskedMobilePhoneNumberOf(account.getPrimaryMobilePhoneNumber());
        return rebuilt;
    }

    private static Integer ageFromDateOfBirth(LocalDate dob) {
        try {
            return Period.between(dob, LocalDate.now()).getYears();
        } catch (NullPointerException ignored) {
            // 数据库中未存储出生日期
        } catch (Exception ignored) {
            // 其他未处理的问题
        }
        return null;
    }

    /**
     * 打码后的姓名, 例如: 张三→张某, 李四→李某, 孙悟空→孙某空, 猪八戒→猪某戒, 六小龄童→六某童
     *
     * @param realName 真实姓名
     * @return 返回打码后的姓名
     */
    private static String maskedNameOf(String realName) {
        int nameLen = realName.length();
        if (nameLen <= 1) {
            return "*";
        }
        String masked = realName.charAt(0) + "某";
        if (nameLen >= 3) {
            masked += realName.charAt(nameLen - 1);
        }
        return masked;
    }

    public Long getId() {
        return id;
    }

    public String getMaskedName() {
        return maskedName;
    }

    public Integer getAge() {
        return age;
    }

    public String getMaskedMobilePhoneNumber() {
        return maskedMobilePhoneNumber;
    }

    /**
     * 对真实手机号码进行打码
     *
     * @param realPhoneNumber 真实手机号码
     * @return 中间4位被*号遮蔽的手机号码
     */
    private static String maskedMobilePhoneNumberOf(String realPhoneNumber) {
        int len = realPhoneNumber.length();
        if (len <= 7) {
            return "***********";
        }
        char[] masked = realPhoneNumber.toCharArray();
        for (int i = 3; i < len - 4; i++) {
            masked[i] = '*';
        }
        return new String(masked);
    }
}
